const Service = require('egg').Service;
const prefix = 'https://api.weixin.qq.com/cgi-bin';
const api = {
    token:`${prefix}/token`,
    jsApiTicket:`${prefix}/ticket/getticket`
}

class wechatService extends Service{
    //access_token
    async getAccessToken () {
        const {ctx} = this;
        const Token = ctx.model.Token;
        let access_token = await Token.getToken('access_token');
        if(this.isValidToken(access_token)){
            return access_token.token;
        }else{
            const url = `${api.token}?grant_type=client_credential&appid=${this.config.wechat.appID}&secret=${this.config.wechat.appSecret}`;
            const res = await ctx.curl(url,{
                dataType:'json'
            });
            if(res!=null&&res.data!=null){
                const data = res.data;
                const token = await Token.saveToken({
                    token:data.access_token,
                    expires_in:(data.expires_in - 20) * 1000 + new Date().getTime()
                },'access_token');
                return token.token;
            }
            return null;
        }
    }
    //jsapi_ticket
    async getJsapiTicket () {
        const {ctx} = this;
        const Token = ctx.model.Token;
        let jsApiTicket = await Token.getToken('jsapi_ticket');
        if(this.isValidToken(jsApiTicket)){
            return jsApiTicket.token;
        }else{
            const access_token = await this.getAccessToken();
            if(access_token ==null){
                return null;
            }
            const url = `${api.jsApiTicket}?access_token=${access_token}&type=jsapi`;
            const res = await ctx.curl(url,{
                dataType:'json'
            });
            if(res!=null&&res.data!=null&&res.data.errcode===0){
                const data = res.data;
                const token = await Token.saveToken({
                    token:data.ticket,
                    expires_in:(data.expires_in - 20) * 1000 + new Date().getTime()
                },'jsapi_ticket');
                return token.token;
            }
            return null;
        }    
    }
    
    isValidToken (token) {
        if(token == null || token.expires_in == null){
            return false;
        }
        if(token.expires_in<=new Date().getTime()){
            return false;
        }
        return true;
    }
}

module.exports = wechatService;